/**
 * 
 */
package com.vector.ding.web.service.bizinfo;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.BizConstant;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.commons.util.file.ExcelUtil;
import com.vector.ding.dao.mybatis.mapper.GqtzgsBizInfoMapper;
import com.vector.ding.dao.mybatis.model.GqtzgsBizInfo;
import com.vector.ding.dao.mybatis.model.GqtzgsBizInfoExample;
import com.vector.ding.exception.BaseException;

/**
 * @author vector
 *
 */
@Service
public class GqtzgsBizInfoMgrService {
	
	@Autowired
	private GqtzgsBizInfoMapper bizMapper;
	
//	public GqtzgsBizInfo getBizInfo(String companyName) { 
//		List<GqtzgsBizInfo> list = getBizInfos(companyName);
//		return CollectionUtil.isEmpty(list) ? null : list.get(0);
//	}
	
	public GqtzgsBizInfo getBizInfo(String companyName, int belongYear) { 
		if (StringUtil.isEmpty(companyName))
			return null;
		
		GqtzgsBizInfoExample example = new GqtzgsBizInfoExample();
		if(belongYear == 0)
		   example.or().andCompanyNameEqualTo(companyName);
		else{
			example.or().andCompanyNameEqualTo(companyName)
			.andBelongYearEqualTo(belongYear);
		}
		List<GqtzgsBizInfo> list = bizMapper.selectByExample(example);
		return CollectionUtil.isEmpty(list) ? null : list.get(0);
	}
	
	public BigDecimal getScore(String companyName) {
		List<GqtzgsBizInfo> list = getBizInfos(companyName);
		if (CollectionUtil.isEmpty(list))
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
		for (GqtzgsBizInfo bizInfo: list) {
			score = score.add(getScore(bizInfo));
		}
		return score;
	}
	
	public BigDecimal getBaseScore(String companyName) {
		List<GqtzgsBizInfo> list = getBizInfos(companyName);
		if (CollectionUtil.isEmpty(list))
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
		for (GqtzgsBizInfo bizInfo: list) {
			BigDecimal revenueGrade = bizInfo.getRevenueGrade();
			if (revenueGrade != null)
				score = score.add(revenueGrade);
		}
		return score;
	}
	
	public BigDecimal getScore(String companyName, int belongYear) {
		GqtzgsBizInfo bizInfo = getBizInfo(companyName, belongYear);
		if (bizInfo == null)
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
//		BigDecimal revenueGrade = bizInfo.getRevenueGrade();
//		if (revenueGrade != null)
//			score = score.add(revenueGrade);
		BigDecimal externalInvestGrade = bizInfo.getExternalInvestGrade();
		if (externalInvestGrade != null)
			score = score.add(externalInvestGrade);
		BigDecimal exitProjectGrade = bizInfo.getExitProjectGrade();
		if (exitProjectGrade != null)
			score = score.add(exitProjectGrade);
		BigDecimal grateOrg1Grade = bizInfo.getGrateOrg1Grade();
		if (grateOrg1Grade != null)
			score = score.add(grateOrg1Grade);
		BigDecimal grateOrg2Grade = bizInfo.getGrateOrg2Grade();
		if (grateOrg2Grade != null)
			score= score.add(grateOrg2Grade);
		
		return score;
	}
	
	public BigDecimal getBaseScore(String companyName, int belongYear) {
		GqtzgsBizInfo bizInfo = getBizInfo(companyName, belongYear);
		if (bizInfo == null)
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
		BigDecimal revenueGrade = bizInfo.getRevenueGrade();
		if (revenueGrade != null)
			score = score.add(revenueGrade);
		
		return score;
	}
	
	public BigDecimal getScore(GqtzgsBizInfo bizInfo) {
		if (bizInfo == null)
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
//		BigDecimal revenueGrade = bizInfo.getRevenueGrade();
//		if (revenueGrade != null)
//			score = score.add(revenueGrade);
		BigDecimal externalInvestGrade = bizInfo.getExternalInvestGrade();
		if (externalInvestGrade != null)
			score = score.add(externalInvestGrade);
		BigDecimal exitProjectGrade = bizInfo.getExitProjectGrade();
		if (exitProjectGrade != null)
			score = score.add(exitProjectGrade);
		BigDecimal grateOrg1Grade = bizInfo.getGrateOrg1Grade();
		if (grateOrg1Grade != null)
			score = score.add(grateOrg1Grade);
		BigDecimal grateOrg2Grade = bizInfo.getGrateOrg2Grade();
		if (grateOrg2Grade != null)
			score= score.add(grateOrg2Grade);
		
		return score;
	}
	public List<GqtzgsBizInfo> getBizInfos(String companyName) { 
		if (StringUtil.isEmpty(companyName))
			return Collections.emptyList();
		
		GqtzgsBizInfoExample example = new GqtzgsBizInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		return bizMapper.selectByExample(example);
	}
	
	public List<GqtzgsBizInfo> getBizInfo(int pageIndex, int pageSize, 
			HttpServletRequest request) {
		PageHelper.startPage(pageIndex, pageSize, true);
		GqtzgsBizInfoExample example = parseBizInfoExample(request);
		//example.setOrderByClause("number asc");
		return bizMapper.selectByExample(example);
	}
	
	private GqtzgsBizInfoExample parseBizInfoExample(HttpServletRequest request) {
		GqtzgsBizInfoExample example = new GqtzgsBizInfoExample();
		String companyName = StringUtil.getString(request.getParameter("company_name"));
		//if (StringUtil.isNotEmpty(companyName))
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return example;
	}
	
	public boolean addBizInfo(GqtzgsBizInfo record) {
		if (StringUtil.isEmpty(record.getNumber()))
			record.setNumber(UUID.randomUUID().toString());
		return 1 == bizMapper.insertSelective(record);
	}
	
	public boolean updateBizInfo(GqtzgsBizInfo record) {
		if (StringUtil.isEmpty(record.getNumber()))
			return false;
		return 1 == bizMapper.updateByPrimaryKeySelective(record);
	}
	
	public void deleteBizInfo(String... nums) {
		if (nums == null)
			return ;
		
		for (String num: nums) {
			bizMapper.deleteByPrimaryKey(num);
		}
	}
	
	public GqtzgsBizInfo parseBizInfo(HttpServletRequest request) {
		GqtzgsBizInfo record = new GqtzgsBizInfo();
		String belongYear = StringUtil.getString(request.getParameter("belongYear"));
		if (StringUtil.isNotEmpty(belongYear))
			record.setBelongYear(new Integer(belongYear));
		String revenue = StringUtil.getString(request.getParameter("revenue"));
		if (StringUtil.isNotEmpty(revenue))
			record.setRevenue(new BigDecimal(revenue));
		String revenueGrade = StringUtil.getString(request.getParameter("revenueGrade"));
		if (StringUtil.isNotEmpty(revenueGrade))
			record.setRevenueGrade(new BigDecimal(revenueGrade));
		record.setCompanyName(request.getParameter("companyName"));
		String exitProjectGrade = request.getParameter("exitProjectGrade");
		if(StringUtil.isNotEmpty(exitProjectGrade))
		   record.setExitProjectGrade(new BigDecimal(exitProjectGrade));
		String exitProjectScale = request.getParameter("exitProjectScale");
		if(StringUtil.isNotEmpty(exitProjectScale))
		   record.setExitProjectScale(new BigDecimal(exitProjectScale));
		String externalInvestGrade = request.getParameter("externalInvestGrade");
		if(StringUtil.isNotEmpty(externalInvestGrade))
		   record.setExternalInvestGrade(new BigDecimal(externalInvestGrade));
		String externalInvestScale = request.getParameter("externalInvestScale");
		if(StringUtil.isNotEmpty(externalInvestScale))
		   record.setExternalInvestScale(new BigDecimal(externalInvestScale));
		String grateOrg1Grade = request.getParameter("grateOrg1Grade");
		if(StringUtil.isNotEmpty(grateOrg1Grade))
		   record.setGrateOrg1Grade(new BigDecimal(grateOrg1Grade));
		String grateOrg1InvestScale = request.getParameter("grateOrg1InvestScale");
		if(StringUtil.isNotEmpty(grateOrg1InvestScale))
		   record.setGrateOrg1InvestScale(new BigDecimal(grateOrg1InvestScale));
		String grateOrg2Grade = request.getParameter("grateOrg2Grade");
		if(StringUtil.isNotEmpty(grateOrg2Grade))
		   record.setGrateOrg2Grade(new BigDecimal(grateOrg2Grade));
		String grateOrg2InvestScale = request.getParameter("grateOrg2InvestScale");
		if(StringUtil.isNotEmpty(grateOrg2InvestScale))
		   record.setGrateOrg2InvestScale(new BigDecimal(grateOrg2InvestScale));
		String grateOrg2Name = request.getParameter("grateOrg2Name");
		if(StringUtil.isNotEmpty(grateOrg2Name))
		   record.setGrateOrg2Name(grateOrg2Name);
		String greatOrg1Name = request.getParameter("greatOrg1Name");
		if(StringUtil.isNotEmpty(greatOrg1Name))
		   record.setGreatOrg1Name(greatOrg1Name);
		if (StringUtil.isEmpty(request.getParameter("id")))
			record.setId(UUID.randomUUID().toString());
		else
			record.setId(request.getParameter("id"));
		if (StringUtil.isNotEmpty(request.getParameter("number")))
			record.setNumber(request.getParameter("number"));
		
		return record;
	}
	
	public void importFormFile(File importFile) {
		HSSFWorkbook workBook = null;
		int rowIndex = 0;
		try {
			workBook = new HSSFWorkbook(FileUtils.openInputStream(importFile));
			HSSFSheet sheet = workBook.getSheetAt(1);
			HSSFRow titleRow = sheet.getRow(4);
			for (int cellIdx = titleRow.getFirstCellNum(); cellIdx < titleRow.getLastCellNum(); ++cellIdx) {
				System.out.println(titleRow.getCell(cellIdx).toString());
			}
			int rowNum = sheet.getLastRowNum();
			for (rowIndex = 4; rowIndex <= rowNum; ++rowIndex) {
				HSSFRow row = sheet.getRow(rowIndex);
				boolean needImport = checkRowData(row);
				if (!needImport)
					continue;
				
				GqtzgsBizInfo bean = getBizInfoBean(row);
				bizMapper.insertSelective(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
//			throw new BaseException(e);
			throw new BaseException(String.format("第%s行数据格式有误，请检查数据！", rowIndex));
		} finally {
			if (workBook != null) {
				try {
					workBook.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BaseException(e);
				}
			}
		}
	}
	
	public GqtzgsBizInfo getBizInfoBean(HSSFRow row) {
		GqtzgsBizInfo bean = new GqtzgsBizInfo();
		bean.setId(UUID.randomUUID().toString());
		bean.setNumber(UUID.randomUUID().toString());
		bean.setCompanyName(ExcelUtil.getStringValue(row.getCell(BizConstant.Gqtzgs.Biz.COMPANY_NAME_CELL),false));
		bean.setBelongYear(ExcelUtil.getIntegerValue(row.getCell(BizConstant.Gqtzgs.Biz.BELONG_YEAR_CELL)));
		bean.setRevenue(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.REVENUE_CELL).getNumericCellValue()));
		bean.setRevenueGrade(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.REVENUE_GRADE_CELL).getNumericCellValue()));
		bean.setExitProjectGrade(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.EXIT_PROJECT_GRADE_CELL).getNumericCellValue()));
		bean.setExitProjectScale(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.EXIT_PROJECT_SCALE_CELL).getNumericCellValue()));
		bean.setExternalInvestGrade(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.EXTERNAL_INVEST_GRADE_CELL).getNumericCellValue()));
		bean.setExternalInvestScale(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.EXTERNAL_INVEST_SCALE_CELL).getNumericCellValue()));
		bean.setGreatOrg1Name(ExcelUtil.getStringValue(row.getCell(BizConstant.Gqtzgs.Biz.GREAT_ORG_1_NAME_CELL),false));
		bean.setGrateOrg1Grade(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.GRATE_ORG_1_GRADE_CELL).getNumericCellValue()));
		bean.setGrateOrg1InvestScale(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.GRATE_ORG_1_INVEST_SCALE_CELL).getNumericCellValue()));
		bean.setGrateOrg2Name(ExcelUtil.getStringValue(row.getCell(BizConstant.Gqtzgs.Biz.GREAT_ORG_2_NAME_CELL),false));
		bean.setGrateOrg2Grade(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.GRATE_ORG_2_GRADE_CELL).getNumericCellValue()));
		bean.setGrateOrg2InvestScale(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Biz.GRATE_ORG_2_INVEST_SCALE_CELL).getNumericCellValue()));
		return bean;
	}
	
	private boolean checkRowData(HSSFRow row) {
		String companyName = row.getCell(BizConstant.Gqtzgs.Biz.COMPANY_NAME_CELL).toString();
		if (StringUtil.isEmpty(companyName))
			return false;
		
		GqtzgsBizInfoExample example = new GqtzgsBizInfoExample();
		example.or().andNumberEqualTo(companyName);
		return bizMapper.countByExample(example) == 0;
	}
}
